<template>
  <div v-if="createAuth">
    <page-header :title="$t('m.Invitation_rules')" is-emphasize>
      <el-button @click="submit()">{{ $t('m.save') }}</el-button>
    </page-header>
    <div class="detail_div container">
      <div class="detail_left">
        <div class="detail_left_div" style=" padding-bottom: 20px;">
          <el-form
            label-position="top"
            :model="ruleForm"
            :rules="rules"
            ref="ruleForm1"
            ><div class="create_title">{{ $t('m.Invitation_rules') }}</div>
            <div style="display:flex;">
              <div class="create_title2">{{ $t('m.Invitation_rewards') }}*</div>
              <el-tooltip
                class="item"
                effect="dark"
                :content="$t('m.Invitation_rewards_friend')"
                placement="top-start"
              >
                <img
                  src="@/assets/imgs/ic_mark@2x.png"
                  style="width:16px;height:16px;vertical-align:middle;position: relative;top:1px;"
                />
              </el-tooltip>
            </div>
            <el-form-item prop="type">
              <el-checkbox-group v-model="ruleForm.type">
                <el-checkbox name="type" :label="'1'">{{
                  $t('m.Reward_points')
                }}</el-checkbox>
              </el-checkbox-group>
              <el-form-item
                prop="point"
                key="point"
                v-if="ruleForm.type.includes('1')"
              >
                <el-input
                  style="width:444px;"
                  v-model="ruleForm.point"
                  @input="changePoint"
                  :placeholder="$t('m.Please_enter')"
                  clearable
                  maxlength="3"
                ></el-input>
              </el-form-item>
              <el-form-item v-else>
                <el-input
                  style="width:444px;"
                  v-model="ruleForm.point"
                  @input="changePoint"
                  :placeholder="$t('m.Please_enter')"
                  clearable
                  maxlength="3"
                ></el-input>
              </el-form-item>
              <div style="display:flex;">
                <div style="margin-right:20px;">
                  <el-checkbox-group v-model="ruleForm.type">
                    <el-checkbox name="type" :label="'2'">{{
                      $t('m.Coupon_rewards')
                    }}</el-checkbox>
                  </el-checkbox-group>
                  <el-form-item
                    prop="couponId"
                    v-if="ruleForm.type.includes('2')"
                    key="couponId"
                    style="margin-bottom:0"
                  >
                    <el-select
                      v-model="ruleForm.couponId"
                      clearable
                      filterable
                      :placeholder="$t('m.pleaseChoose')"
                      style="width:100%;"
                    >
                      <el-option
                        v-for="item in couponOptions"
                        :key="item.id"
                        :label="
                          item.deductionType == 1
                            ? $t('m.system_FreeDuration') +
                              ' ' +
                              item.deduction.type1FreeDurationVal +
                              $format.stateFormat(
                                item.deduction.type1FreeDurationUnit,
                                item.deduction.type1FreeDurationVal > 1
                                  ? optionsTime1
                                  : optionsTime2
                              )
                            : item.deductionType == 2
                            ? $t('m.couponAmount') +
                              ' ' +
                              $format.amountFormat(
                                item.deduction.type2DiscountAmount
                              )
                            : item.deductionType == 3
                            ? $t('m.Rent_discount') +
                              ' ' +
                              item.deduction.type3DiscountAmount +
                              '%'
                            : ''
                        "
                        :value="item.id"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item v-else style="margin-bottom:0">
                    <el-select
                      v-model="ruleForm.couponId"
                      clearable
                      filterable
                      :placeholder="$t('m.pleaseChoose')"
                      style="width:100%;"
                    >
                      <el-option
                        v-for="item in couponOptions"
                        :key="item.id"
                        :label="
                          item.deductionType == 1
                            ? $t('m.system_FreeDuration') +
                              ' ' +
                              item.deduction.type1FreeDurationVal +
                              $format.stateFormat(
                                item.deduction.type1FreeDurationUnit,
                                item.deduction.type1FreeDurationVal > 1
                                  ? optionsTime1
                                  : optionsTime2
                              )
                            : item.deductionType == 2
                            ? $t('m.couponAmount') +
                              ' ' +
                              $format.amountFormat(
                                item.deduction.type2DiscountAmount
                              )
                            : item.deductionType == 3
                            ? $t('m.Rent_discount') +
                              ' ' +
                              item.deduction.type3DiscountAmount +
                              '%'
                            : ''
                        "
                        :value="item.id"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                </div>
                <div>
                  <div
                    class="create_title4"
                    style="color:#646b80;padding-bottom:12px;font-weight: 400;line-height:19px;"
                  >
                    {{ $t('m.Number_of_coupons') }}
                  </div>
                  <el-form-item
                    prop="quantity"
                    v-if="ruleForm.type.includes(2)"
                    key="quantity"
                    style="margin-bottom:0"
                  >
                    <el-input
                      v-model="ruleForm.quantity"
                      @input="changeCouponNum"
                      :placeholder="$t('m.Please_enter')"
                      clearable
                      maxlength="2"
                      class="currency_input"
                    ></el-input>
                  </el-form-item>
                  <el-form-item v-else style="margin-bottom:0">
                    <el-input
                      v-model="ruleForm.quantity"
                      @input="changeCouponNum"
                      :placeholder="$t('m.Please_enter')"
                      clearable
                      maxlength="2"
                      class="currency_input"
                    ></el-input>
                  </el-form-item>
                </div>
              </div>
            </el-form-item>

            <el-form-item
              :label="$t('m.Activity_period_of_inviting_friends') + '*'"
              :style="ruleForm.state == 1 ? 'margin-bottom:0;' : ''"
            >
              <el-radio-group v-model="ruleForm.state">
                <el-radio :label="1">{{ $t('m.Validity_period') }}</el-radio>
                <el-radio :label="2">{{ $t('m.Permanent2') }}</el-radio>
                <el-radio :label="3">{{ $t('m.Offline_coupon') }}</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item v-if="ruleForm.state == 1" prop="times" key="times">
              <el-date-picker
                v-model="ruleForm.times"
                @input="choiceTimes"
                style="width: 444px;"
                :picker-options="pickerBeginDateBefore"
                type="daterange"
                :default-time="['00:00:00', '23:59:59']"
                value-format="timestamp"
                range-separator="~"
                :start-placeholder="$t('m.start_date')"
                :end-placeholder="$t('m.end_date')"
              >
              </el-date-picker>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div class="detail_right">
        <div class="detail_left_div" style=" padding-bottom: 20px;">
          <el-form
            label-position="top"
            :model="ruleForm"
            :rules="rules"
            ref="ruleForm2"
          >
            <div class="create_title">
              {{ $t('m.Introduction_for_inviting_friends') }}*
            </div>
            <div class="create_title2">Tiếng Việt*</div>
            <el-form-item prop="description.vi">
              <el-input
                v-model="ruleForm.description.vi"
                :placeholder="$t('m.Please_enter')"
                :autosize="{ minRows: 4, maxRows: 6 }"
                type="textarea"
                clearable
                maxlength="200"
              ></el-input>
            </el-form-item>
            <div class="create_title2">简体中文*</div>
            <el-form-item prop="description.zh">
              <el-input
                v-model="ruleForm.description.zh"
                :placeholder="$t('m.Please_enter')"
                :autosize="{ minRows: 4, maxRows: 6 }"
                type="textarea"
                clearable
                maxlength="200"
              ></el-input>
            </el-form-item>
            <div class="create_title2">English*</div>
            <el-form-item prop="description.en">
              <el-input
                v-model="ruleForm.description.en"
                :placeholder="$t('m.Please_enter')"
                :autosize="{ minRows: 4, maxRows: 6 }"
                type="textarea"
                clearable
                maxlength="200"
              ></el-input>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data () {
    return {
      pickerBeginDateBefore: {
        disabledDate (time) {
          return time.getTime() < Date.now() - 24 * 60 * 60 * 1000
        }
      },
      couponOptions: [],
      ruleForm: {
        amount: '', // 金额
        couponId: '', //	优惠券id
        createTime: '',
        couponReward: false, //	是否优惠券奖励
        description: {
          de: '', //	德语
          en: '', //	英文
          fr: '', //	法语
          vi: '', //	
          it: '', //	
          vi: '', //	越南语
          zh: '' //	中文
        },
        endTime: '', //	结束时间
        id: '',
        inviteeNum: '', // 邀请人数
        platformId: 1,
        point: '', //	积分数
        pointReward: false, //	是否积分奖励
        quantity: '', //	优惠券数量
        remark: '', // 备注
        startTime: '', //	起始时间
        state: 1, // 状态：1-上架（有效时间） 2-永久上架 3-下架
        type: [], // 	奖励类型 ：1-积分 2-优惠券，逗号分割
        updateTime: '',
        times: ''
      },

      optionsTime1: [
        { value: '1', label: ' ' + this.$t('m.minute3') },
        { value: '2', label: ' ' + this.$t('m.hour4') }
      ],
      optionsTime2: [
        { value: '1', label: ' ' + this.$t('m.minute2') },
        { value: '2', label: ' ' + this.$t('m.hour3') }
      ],

      rules: {
        point: [
          {
            required: true,
            message: this.$t('m.Please_enter_point_value'),
            trigger: 'blur'
          }
        ],
        quantity: [
          {
            required: true,
            message: this.$t('m.Please_set_reward_coupon'),
            trigger: 'blur'
          }
        ],
        couponId: [
          {
            required: true,
            message: this.$t('m.Please_set_reward_coupon'),
            trigger: 'change'
          }
        ],
        type: [
          {
            type: 'array',
            required: true,
            message: this.$t('m.Please_select_invitation_rewards'),
            trigger: 'change'
          }
        ],
        times: [
          {
            required: true,
            message: this.$t('m.Please_set_expiry_date'),
            trigger: 'change'
          }
        ],
        'description.vi': [
          {
            required: true,
            message: this.$t('m.Please_enter_introduction_inviting_friends'),
            trigger: 'blur'
          }
        ],
        'description.en': [
          {
            required: true,
            message: this.$t('m.Please_enter_introduction_inviting_friends'),
            trigger: 'blur'
          }
        ],
        'description.zh': [
          {
            required: true,
            message: this.$t('m.Please_enter_introduction_inviting_friends'),
            trigger: 'blur'
          }
        ]
      },
      createAuth: this.permissionsId(203)
    }
  },

  created () {
    if (!this.createAuth) {
      return
    }
    this.getLast()
    this.getCouponId()
  },
  mounted () {},
  methods: {
    getLast () {
      this.$api.invitation.getLatest().then(res => {
        if (this.$ok(res)) {
          this.ruleForm = res.data
          this.ruleForm.type = res.data.type.split(',')
          if (res.data.state != 1) {
            this.$set(this.ruleForm, 'times', '')
          } else {
            this.$set(this.ruleForm, 'times', [
              res.data.startTime,
              res.data.endTime
            ])
          }
        }
      })
    },
    getCouponId () {
      this.$api.invitation.getCouponId().then(res => {
        if (this.$ok(res)) {
          this.couponOptions = res.data
        }
      })
    },
    //限制积分输入
    changePoint (val) {
      this.ruleForm.point = this.$check.noZero(val)
    },
    //限制优惠券数量输入
    changeCouponNum (val) {
      this.ruleForm.quantity = this.$check.noZero(val)
    },
    // 选择搜索日期
    choiceTimes (value) {
      // console.log(this.ruleForm.times, value)
      if (value) {
        this.ruleForm.startTime = this.ruleForm.times[0]
        this.ruleForm.endTime = this.ruleForm.times[1]
      } else {
        this.ruleForm.startTime = ''
        this.ruleForm.endTime = ''
      }
      this.$forceUpdate()
    },
    // 创建/编辑
    async submit () {
      try {
        await Promise.all([
          this.$refs.ruleForm1.validate(),
          this.$refs.ruleForm2.validate()
        ])
        this.$openLoading()
        let params = { ...this.ruleForm }
        delete params.times
        delete params.updateTime
        params.type = params.type.join(',')
        console.log(this.ruleForm)
        if (this.ruleForm.state != 1) {
          params.endTime = ''
          params.startTime = ''
        }
        // console.log(this.ruleForm, params)
        this.$api.invitation.updateRule(params).then(res => {
          this.$closeLoading()
          if (this.$ok(res)) {
            this.$router.go(-1)
            this.$message.success(res.message)
          } else {
            this.$message.error(res.message)
          }
        })
      } catch (error) {
        // 验证失败
        // console.log('error submit !')
        return
      }
    }
  }
}
</script>

<style scoped lang="scss">
.detail_left_div {
  ::v-deep .el-checkbox-group {
    margin-bottom: 12px;
  }
}
.el-form-item.is-error .el-input__inner,
.el-form-item.is-error .el-input__inner:focus,
.el-form-item.is-error .el-textarea__inner,
.el-form-item.is-error .el-textarea__inner:focus {
  border-color: #fd5849 !important;
}
</style>
